package net.mikoo.seals.api.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.api.model.BaseResponse;
import net.mikoo.seals.api.model.ResultType;
import net.mikoo.seals.api.model.apply.ApplyRecordRequest;
import net.mikoo.seals.api.model.apply.ApplyRecordResponse;
import net.mikoo.seals.api.model.apply.ApplyRequest;
import net.mikoo.seals.api.model.apply.GetApplyDetailRequest;
import net.mikoo.seals.api.model.apply.GetApplyDetailResponse;
import net.mikoo.seals.api.model.apply.RetractRequest;
import net.mikoo.seals.api.utility.PartyUtility;
import net.mikoo.seals.biz.service.ApplyServices;
import net.mikoo.seals.common.enums.ApplyTypeEnum;
import net.mikoo.seals.common.exception.NeedBackMsgException;
import net.mikoo.seals.common.model.PageModel;
import net.mikoo.seals.model.Apply;
import net.mikoo.seals.model.ApplyQuery;
import net.mikoo.seals.model.ApplyVerify;
import net.mikoo.seals.model.Upfile;

@Controller
public class ApplyController {

	private static Logger logger = LoggerFactory.getLogger(ApplyController.class);
	
	@Autowired
	private ApplyServices applyService;
	
	@RequestMapping("/apply/apply")
	@ResponseBody
	public BaseResponse apply(ApplyRequest request, HttpServletRequest httpRequest) {
		
		BaseResponse result = new BaseResponse();
		try {
			
			if(request == null) {
				throw new IllegalArgumentException("request");
			}
			
			ApplyTypeEnum applyType = ApplyTypeEnum.getByCode(request.getType());
			
			Apply apply = new Apply();
			apply.setCompanyId(PartyUtility.getCurrentPartyCompanyId(httpRequest));
			apply.setApplyType(request.getType());
			apply.setCause(request.getCause());
			apply.setPartyId(PartyUtility.getCurrentPartyId(httpRequest));
			apply.setDevicesId(request.getDevicesId());
			apply.setSealId(request.getSealId());
			apply.setApplyTimes(request.getTimes());
			apply.setSealId(request.getSealId());
			apply.setVerifys(new ArrayList<ApplyVerify>());
			apply.setUseSpecial(request.getUseSpecial());
			apply.setTakeDestination(request.getAddress());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(!StringUtils.isBlank(request.getTakeStartTime())) {
				apply.setTakeStartTime(sdf.parse(request.getTakeStartTime()));
			}
			
			if(!StringUtils.isBlank(request.getTakeEndTime())) {
				apply.setTakeEndTime(sdf.parse(request.getTakeEndTime()));
			}
			
			if(StringUtils.isNotBlank(request.getVoucherUrls())) {
				List<Long> voucherUrls = new ArrayList<Long>();
				for(String voucherUrl : request.getVoucherUrls().split(",")) {
					voucherUrls.add(Long.valueOf(voucherUrl));
				}
				apply.setUpfileIds(voucherUrls);
			}
			
			applyService.apply(apply);
			result.setResult(ResultType.SUCCESS.getValue());
		}catch(NeedBackMsgException ne) {
			logger.error("", ne);
			result.setResult(ResultType.ERROR.getValue());
			result.setErrorMsg(ne.getMessage());
		}catch(Exception e) {
			logger.error("", e);
			result.setResult(ResultType.ERROR.getValue());
		}
		
		return result;
	}
	
	@RequestMapping("/apply/record")
	@ResponseBody
	public ApplyRecordResponse applyRecord(ApplyRecordRequest request, HttpServletRequest httpRequest) {
		ApplyRecordResponse result = new ApplyRecordResponse();
		try {
			
			if(request == null) {
				throw new IllegalArgumentException("request");
			}
			
			if(request.getPageNo() == null || request.getPageNo() < 1) {
				request.setPageNo(1);
			}
			
			if(request.getPageSize() == null || request.getPageSize() < 1) {
				request.setPageSize(10);
			}
			
			Long partyId = PartyUtility.getCurrentPartyId(httpRequest);
			if(partyId == null) {
				throw new IllegalArgumentException("partyId");
			}
			
			ApplyQuery applyQuery = new ApplyQuery();
			if(request.getDevicesId() != null) {
				applyQuery.setDevicesId(request.getDevicesId());
			}else {
				applyQuery.setPartyId(partyId);
			}
			applyQuery.setCompanyId(PartyUtility.getCurrentPartyCompanyId(httpRequest));
			applyQuery.setApplyStatus(request.getStatus());
			applyQuery.setOrderColumn("apply_id");
			applyQuery.setOrderType("desc");
			applyQuery.setOffset((request.getPageNo() - 1) * request.getPageSize());
			applyQuery.setPageSize(request.getPageSize());
			
			PageModel<Apply> pm = applyService.getPageByQuery(applyQuery);
			if(pm != null) {
				result = ApplyRecordResponse.valueOf(pm);
			}
			
			result.setResult(ResultType.SUCCESS.getValue());
		}catch(Exception e) {
			logger.error("", e);
			result.setResult(ResultType.ERROR.getValue());
		}
		return result;
	}
	
	@RequestMapping("/apply/detail")
	@ResponseBody
	public GetApplyDetailResponse detail(GetApplyDetailRequest request, HttpServletRequest httpRequest) {
		GetApplyDetailResponse result = new GetApplyDetailResponse();
		try {
			
			if(request == null) {
				throw new IllegalArgumentException("request");
			}
			
			if(request.getApplyId() == null) {
				throw new IllegalArgumentException("request.getApplyId");
			}
			
			Long partyId = PartyUtility.getCurrentPartyId(httpRequest);
			if(partyId == null) {
				throw new IllegalArgumentException("partyId");
			}
			
			Apply apply = applyService.getById(request.getApplyId());
			if(apply != null && apply.getApplyId().equals(request.getApplyId())) {
				List<Upfile> upfiles = applyService.getApplyfiles(request.getApplyId());
				apply.setUpfiles(upfiles);
				result = GetApplyDetailResponse.valueOf(apply);
			}
			result.setResult(ResultType.SUCCESS.getValue());
		}catch(Exception e) {
			logger.error("", e);
			result.setResult(ResultType.ERROR.getValue());
		}
		return result;
	}
	
	@RequestMapping("/apply/retract")
	@ResponseBody
	public BaseResponse retract(RetractRequest request, HttpServletRequest httpRequest) {
		BaseResponse result = new BaseResponse();
		try {
			
			if(request == null) {
				throw new IllegalArgumentException("request");
			}
			
			if(request.getApplyId() == null) {
				throw new IllegalArgumentException("request.getApplyId");
			}
			
			ApplyQuery query = new ApplyQuery();
			query.setApplyId(request.getApplyId());
			query.setCompanyId(PartyUtility.getCurrentPartyCompanyId(httpRequest));
			query.setPartyId(PartyUtility.getCurrentPartyId(httpRequest));
			applyService.retract(query);
			result.setResult(ResultType.SUCCESS.getValue());
		}catch(Exception e) {
			logger.error("", e);
			result.setResult(ResultType.ERROR.getValue());
		}
		return result;
	}
	
}
